package com.xf.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xf.common.core.domain.Constants;
import com.xf.common.core.domain.DmpResult;
import com.xf.common.core.entity.dmp.DmpAuthResource;
import com.xf.common.core.entity.dmp.DmpAuthResourceRole;
import com.xf.common.core.entity.dmp.DmpAuthRole;
import com.xf.common.core.enums.UserCacheKeyEnum;
import com.xf.common.redis.cache.DmpRedisCache;
import com.xf.mapper.DmpAuthResourceMapper;
import com.xf.service.DmpAuthResourceService;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * @author JoeyLiu
 * @create 2022-04-20 16:31
 */
@Service
public class DmpAuthResourceServiceImpl extends ServiceImpl<DmpAuthResourceMapper, DmpAuthResource> implements DmpAuthResourceService {

    @Resource
    private DmpAuthResourceMapper dmpAuthResourceMapper;

    @Resource
    private DmpRedisCache redisCache;

    @Override
    public List<DmpAuthResourceRole> getAllResourceRole() {
        return redisCache.getEx(UserCacheKeyEnum.RESOURCE.getKey("ALL"),
                Duration.ofSeconds(Constants.USER_TIME_OUT), () -> dmpAuthResourceMapper.getallResourceRole());


    }

    @Transactional
    @Override
    public void batchAddRoleResource(List<DmpAuthRole> dmpAuthRoles) {

        if (CollectionUtils.isEmpty(dmpAuthRoles)) {
            return;
        }

        /*//1.删除角色对应资源
        List<Long> roleIds = dmpAuthRoles.stream().map(BaseEntity::getId).collect(Collectors.toList());
        roleResourceRelationService.remove(new LambdaQueryWrapper<DmpAuthRoleResourceRelation>().in(DmpAuthRoleResourceRelation::getRoleId, roleIds));

        //2.添加角色资源关系
        List<DmpAuthRoleResourceRelation> relations = new ArrayList<>();
        for (DmpAuthRole dmpAuthRole : dmpAuthRoles) {
            if (CollectionUtils.isEmpty(dmpAuthRole.getDmpAuthResources())) {
                continue;
            }
            for (DmpAuthResource dmpAuthResource : dmpAuthRole.getDmpAuthResources()) {
                DmpAuthRoleResourceRelation resourceRelation = new DmpAuthRoleResourceRelation();
                resourceRelation.setResourceId(dmpAuthResource.getId());
                resourceRelation.setRoleId(dmpAuthRole.getId());

                relations.add(resourceRelation);
            }
        }

        roleResourceRelationService.saveBatch(relations);*/
    }

    @Override
    public List<DmpAuthResource> queryResourceByRoleIds(List<Long> roleIds) {

        if (CollectionUtils.isEmpty(roleIds)) {
            return new ArrayList<>();
        }

        /*LambdaQueryWrapper lambdaQueryWrapper = new LambdaQueryWrapper<DmpAuthRoleResourceRelation>().in(DmpAuthRoleResourceRelation::getRoleId, roleIds);
        List<DmpAuthRoleResourceRelation> relations = roleResourceRelationService.list(lambdaQueryWrapper);

        if (CollectionUtils.isEmpty(relations)) {
            return new ArrayList<>();
        }

        Map<Long, Long> resourceIdMap = relations.stream().collect(Collectors.toMap(DmpAuthRoleResourceRelation::getResourceId, DmpAuthRoleResourceRelation::getRoleId, (o, n) -> n));
        List<DmpAuthResource> resources = dmpAuthResourceService.list(new LambdaQueryWrapper<DmpAuthResource>().in(DmpAuthResource::getId, resourceIdMap.keySet()));

        for (DmpAuthResource resource : resources) {
            resource.setRoleId(resourceIdMap.get(resource.getId()));
        }
        return resources;*/
        return null;
    }

    @Override
    public IPage<DmpAuthResource> page(IPage page, String name, String url) {
        return baseMapper.selectPage(page, Wrappers.lambdaQuery(DmpAuthResource.class)
                .like(Objects.nonNull(name), DmpAuthResource::getName, name)
                .like(Objects.nonNull(url), DmpAuthResource::getUrl, url)
                .orderByDesc(DmpAuthResource::getCreatedDate));
    }

    @Override
    public DmpResult insert(DmpAuthResource authResource) {
        try {
            DmpAuthResource resource = baseMapper.getOneByName(authResource.getName());
            if (resource != null) {
                return DmpResult.failed("资源已存在，请勿重复提交");
            }
            baseMapper.insert(authResource);
        } catch (Exception e) {
            log.error("添加失败", e);
        }
        return DmpResult.success("添加成功");

    }

    @Override
    public DmpResult removeByResourceId(Long id) {
        try {
            baseMapper.deleteById(id);
            redisCache.del(UserCacheKeyEnum.RESOURCE.getKey("ALL"));
            return DmpResult.success("删除资源成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return DmpResult.failed("删除资源失败");
        }
    }

    @Override
    public DmpResult updateByResourceId(DmpAuthResource dmpAuthResource) {
        try {
            baseMapper.updateById(dmpAuthResource);
            redisCache.del(UserCacheKeyEnum.RESOURCE.getKey("ALL"));
            return DmpResult.success("修改资源成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            return DmpResult.failed("修改资源失败");
        }

    }

}



